#include "friendadd.h"
#include "ui_friendadd.h"

friendAdd::friendAdd(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::friendAdd)
{
    ui->setupUi(this);
}
friendAdd::friendAdd(QTcpSocket * s, QString Id, QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::friendAdd)
{
    ui->setupUi(this);
    UIDesign::setButtonUI(ui->submit);
    UIDesign::setButtonUI(ui->cancel);
    UIDesign::setLineEditUI(ui->id);
    UIDesign::setLineEditUI(ui->nknm);
    UIDesign::setWindowUI(ui->centralwidget);
    UIDesign::setTransparent(ui->label);
    UIDesign::setTransparent(ui->label_2);
    setWindowFlags(Qt::FramelessWindowHint);
    setFixedSize(this->width(), this->height());
    this->setAttribute(Qt::WA_TranslucentBackground);
    sock = s;
    ID = Id;
}



friendAdd::~friendAdd()
{
    delete ui;
}



void friendAdd::recv()
{

    QByteArray byteRequest;
    byteRequest = sock->readAll();
    QJsonParseError err;
    QJsonDocument document = QJsonDocument::fromJson(byteRequest, &err);
    if(err.error == QJsonParseError::NoError)
    {
        QJsonObject request = document.object();
        QJsonValue Rstatus = request.value("status");
        bool status = Rstatus.toBool();
        if(status)
        {
            QJsonValue Rmesg = request.value("mesg");
            QJsonObject mesg = Rmesg.toObject();
            QJsonValue Rusername = mesg.value("username");
            QString username = Rusername.toString();
            QMessageBox::information(this, "提示", "好友申请已发送。");
            emit(addfriendclose(username, unid, nickname));
            this->close();
        }
        else
        {
            QMessageBox::warning(this, "警告", "申请不被认可！");
        }
    }
    else QMessageBox::warning(this, "警告", "服务器下传失败");

}

void friendAdd::on_submit_clicked()
{
    unid = ui->id->text();
    nickname = ui->nknm->text();
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    connect(sock, SIGNAL(readyRead()), this, SLOT(recv()));
    QJsonObject request;
    request.insert("order", 5);
    request.insert("myid", ID);
    QJsonObject data;
    data.insert("to", ui->id->text());
    data.insert("nickname", ui->nknm->text());
    request.insert("data", data);
    qDebug() << request;
    QJsonDocument document;
    document.setObject(request);
    QByteArray byteRequest = document.toJson();
    sock->write(byteRequest);
}

void friendAdd::on_cancel_clicked()
{
    this->close();
}
